package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderItemDao;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    OrderItemService orderItemService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    WmsFeignService wmsFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    private ThreadLocal<OrderSubmitVo>  confirmVoThreadLocal = new ThreadLocal<>();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();


        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {



            //远程查询会员所有收货地址列表
            RequestContextHolder.setRequestAttributes(requestAttributes);

            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());

            orderConfirmVo.setAddress(address);

        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {

            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程查询购物车所有选中的购物项

            List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems();
            orderConfirmVo.setItems(currentCartItems);

        }, executor).thenRunAsync(()->{
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R hasStock = wmsFeignService.getSkuHasStock(collect);

            List<SkuStockVo> data = hasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if(data!=null){
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                orderConfirmVo.setStocks(map);
            }
        },executor);
        //TODO:


        //feign在远程调用之前构造请求，调用很多的拦截器
        //  RequestInterceptor interceptor
        //查询用户积分

        Integer integration = memberRespVo.getIntegration();

        orderConfirmVo.setIntegration(integration);

        String token = UUID.randomUUID().toString().replace("-", "");

        orderConfirmVo.setOrderToken(token);

        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);

        //其他数据自动计算

        CompletableFuture.allOf(getAddressFuture,cartFuture).get();


        return orderConfirmVo;
    }


    @Override
    @Transactional
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {

        confirmVoThreadLocal.set(orderSubmitVo);

        SubmitOrderResponseVo response = new SubmitOrderResponseVo();

        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());

        //1.验证令牌[令牌的对比和删除必须保证原子性]
        //0-令牌失败 1-令牌成功

        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

        String orderToken = orderSubmitVo.getOrderToken();

        //原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);

        if(result == 0L ){
            //令牌验证失败
            response.setCode(1);
            return response;
        }else {

            //令牌验证成功
            //创建订单
            OrderCreateTo order = createOrder();

            //2.验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();

           if(Math.abs(payAmount.subtract(payPrice).doubleValue())!=0.01){

               //金额对比

               //3.保存订单
               saveOrder(order);

               //4.库存锁定，只要有异常，回滚订单数据
               //订单号、所有订单项信息（skuId,skuNum,num）
               WareSkuLockVo lockVo = new WareSkuLockVo();
               lockVo.setOrderSn(order.getOrder().getOrderSn());

               List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                   OrderItemVo itemVo = new OrderItemVo();
                   itemVo.setSkuId(item.getSkuId());
                   itemVo.setCount(item.getSkuQuantity());
                   itemVo.setTitle(item.getSkuName());
                   return itemVo;

               }).collect(Collectors.toList());

               lockVo.setLocks(locks);
               //TODO:远程锁库存
               R r = wmsFeignService.orderLockStock(lockVo);

               if(r.getCode()==0){
                   //锁定成功
                   response.setOrder(order.getOrder());
                   response.setCode(0);

                   //TODO:远程扣减积分，出异常
                   //TODO: int i = 10/0;
                   return response;

               }else {

                   throw new NoStockException(110L);
                   //锁定失败
//                   response.setCode(3);
//                   return response;
               }


           }else {
               response.setCode(2);
               return response;
           }
        }

//
//        if(redisToken!=null&&orderToken.equals(redisToken)){
//            //令牌验证通过
//            redisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
//
//
//        }else {
//
//
//        }


    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {

        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }

    //保存订单数据
    private void saveOrder(OrderCreateTo order) {

        OrderEntity orderEntity = order.getOrder();

        orderEntity.setModifyTime(new Date());

        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();

        orderItemService.saveBatch(orderItems);

    }

    private OrderCreateTo createOrder(){

        OrderSubmitVo submitVo = confirmVoThreadLocal.get();

        OrderCreateTo orderCreateTo = new OrderCreateTo();

        //1.生成订单号
        String orderSn = IdWorker.getTimeId();

        //2.创建订单
        OrderEntity orderEntity = buildOrder(orderSn);

        //3.获取所有订单项
        List<OrderItemEntity> orderItems = buildOrderItems(orderSn);

        //4.计算价格相关
        computePrice(orderEntity,orderItems);
        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(orderItems);

        return orderCreateTo;


    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItems) {

        //订单的总额：叠加每一个订单项的总额信息
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal  integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");

        for (OrderItemEntity orderItem : orderItems) {
            
            BigDecimal realAmount = orderItem.getRealAmount();
            coupon = coupon.add(orderItem.getCouponAmount());
            integration = integration.add(orderItem.getIntegrationAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());

            total = total.add(realAmount);
            if(orderItem.getGiftIntegration()!=null){

                gift = gift.add(new BigDecimal(orderItem.getGiftIntegration().toString()));
            }
            if(orderItem.getGiftGrowth()!=null){

                growth = growth.add(new BigDecimal(orderItem.getGiftGrowth().toString()));
            }


        }
        //1.订单价格相关
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        //
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);

        //积分信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0);
    }

    private OrderEntity buildOrder( String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);

        orderEntity.setMemberId(memberRespVo.getId());

        //获取收货地址

        OrderSubmitVo submitVo = confirmVoThreadLocal.get();

        R fare = wmsFeignService.getFare(submitVo.getAddrId());

        FareVo fareResponse = fare.getData(new TypeReference<FareVo>() {
        });

        //设置运费信息
        orderEntity.setFreightAmount(fareResponse.getFare());
        //设置收货人信息
        orderEntity.setReceiverCity(fareResponse.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(fareResponse.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fareResponse.getAddress().getName());
        orderEntity.setReceiverPhone(fareResponse.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fareResponse.getAddress().getPostCode());
        orderEntity.setReceiverProvince(fareResponse.getAddress().getProvince());
        orderEntity.setReceiverRegion(fareResponse.getAddress().getRegion());

        //设置订单的状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);

        return orderEntity;
    }

    //构建订单项数据
    private List<OrderItemEntity> buildOrderItems(String orderSn) {

        //获取到所有的订单项
        List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems();

        if(currentCartItems!=null&&currentCartItems.size()>0){
            List<OrderItemEntity> itemEntities = currentCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);

                itemEntity.setOrderSn(orderSn);

                return itemEntity;
            }).collect(Collectors.toList());

            return itemEntities;
        }

        return null;
    }

    //构建某一个订单项
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {

        OrderItemEntity itemEntity = new OrderItemEntity();
        //1.订单信息，订单号
        //2.商品的Spu信息
         Long skuId = cartItem.getSkuId();
        R infoBySkuId = productFeignService.getSpuInfoBySkuId(skuId);

        SpuInfoVo data = infoBySkuId.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());

        //3.商品的sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //4.优惠信息不做
        //5.积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //6.订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0.0"));
        itemEntity.setCouponAmount(new BigDecimal("0.0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0.0"));
        //当前订单项的实际金额
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
      
        //总额减各种优惠
        BigDecimal subtract = orign.subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);

        return itemEntity;
    }

}